package com.sheng.project.utils;

import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.Security;
import java.util.Arrays;
import java.util.UUID;

/**
 * @author liusheng
 * @date 2022/09/07
 */
@Slf4j
public class AESUtil {
    private static final String KEY_ALGORITHM = "AES";
    private static final String ALGORITHM_STR = "AES/CBC/PKCS7Padding";
    private static Key key;
    private static Cipher cipher;

    private static void init(byte[] keyBytes) {
        // 如果密钥不足16位，那么就补足. 这个if 中的内容很重要
        int base = 16;
        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 转化成JAVA的密钥格式
        key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
        try {
            // 初始化cipher
            cipher = Cipher.getInstance(ALGORITHM_STR, "BC");
        } catch (Exception e) {
            log.info("初始化加密器失败", e);
            throw new RuntimeException("初始化加密器失败!");
        }
    }

    /**
     * 加密方法
     *
     * @param decryptedData 要加密的字符串
     * @param keyBytes      加密密钥
     * @param ivs           自定义对称解密算法初始向量
     * @return
     */
    public static byte[] encryptOfDiyIV(byte[] decryptedData, byte[] keyBytes, byte[] ivs) {
        byte[] encryptedText = null;
        init(keyBytes);
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(ivs));
            encryptedText = cipher.doFinal(decryptedData);
        } catch (Exception e) {
            log.info("加密失败", e);
            throw new RuntimeException("加密失败!");
        }
        return encryptedText;
    }

    /**
     * 解密方法
     *
     * @param encryptedData 要解密的字符串
     * @param keyBytes      解密密钥
     * @param ivs           自定义对称解密算法初始向量 iv
     * @return 解密后的字节数组
     */
    private static byte[] decryptOfDiyIV(byte[] encryptedData, byte[] keyBytes, byte[] ivs) {
        byte[] encryptedText = null;
        init(keyBytes);
        try {
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivs));
            encryptedText = cipher.doFinal(encryptedData);
        } catch (Exception e) {
            log.info("解密失败", e);
            throw new RuntimeException("解密失败!");
        }
        return encryptedText;
    }

    public static String decryptData(String encryptDataB64, String sessionKeyB64, String ivB64) {
        return new String(decryptOfDiyIV(Base64.decode(encryptDataB64), Base64.decode(sessionKeyB64), Base64.decode(ivB64)));
    }

    public static String encryptData(String encryptDataB64, String sessionKeyB64, String ivB64) {
        return Base64.encode(encryptOfDiyIV(Base64.decode(encryptDataB64), Base64.decode(sessionKeyB64), Base64.decode(ivB64)));
    }

    /**
     * 获取随机key
     *
     * @return 随机key
     */
    public static String getKey() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    /**
     * 将 byte[] 转为各种进制的字符串
     *
     * @param bytes byte[]
     * @param radix 可以转换进制的范围，从 Character.MIN_RADIX 到 Character.MAX_RADIX，超出范围后变为 10 进制
     * @return 转换后的字符串
     */
    public static String binary(byte[] bytes, int radix) {
        // 这里的 1 代表正数
        return new BigInteger(1, bytes).toString(radix);
    }

    /**
     * base 64 encode
     *
     * @param bytes 待编码的 byte[]
     * @return 编码后的 base 64 code
     */
    public static String base64Encode(byte[] bytes) {
        return java.util.Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * base 64 decode
     *
     * @param base64Code 待解码的 base 64 code
     * @return 解码后的 byte[]
     * @throws Exception e
     */
    public static byte[] base64Decode(String base64Code) throws Exception {
        java.util.Base64.Decoder decoder = java.util.Base64.getDecoder();
        return StringUtils.isEmpty(base64Code) ? null : decoder.decode(base64Code);
    }


    /**
     * AES 加密
     *
     * @param content    待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的 byte[]
     * @throws Exception e
     */
    public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        return cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
    }


    /**
     * AES 加密为 base 64 code
     *
     * @param content    待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的 base 64 code
     * @throws Exception e
     */
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        if (StringUtils.isBlank(encryptKey)) {
            return content;
        }
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }

    /**
     * AES 解密
     *
     * @param encryptBytes 待解密的 byte[]
     * @param decryptKey   解密密钥
     * @return 解密后的 Strings
     * @throws Exception e
     */
    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);

        Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }


    /**
     * 将 base 64 code AES 解密
     *
     * @param encryptStr 待解密的 base 64 code
     * @param decryptKey 解密密钥
     * @return 解密后的 string
     * @throws Exception e
     */
    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
        if (StringUtils.isBlank(decryptKey)) {
            return encryptStr;
        }
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
    }

    public static void main(String[] args) {
        String iv = "1234432112344444";
        String key = "sadhowadaskd123sxdaj122sa12";
        String string = "!@#$测试1234asdvcz";
        System.out.println("原文:" + string);
        String code = encryptData(Base64.encode(string.getBytes()), Base64.encode(key.getBytes()), Base64.encode(iv.getBytes()));
        System.out.println("密文:" + code);
        String result = decryptData(code, Base64.encode(key.getBytes()), Base64.encode(iv.getBytes()));
        System.out.println("解密:" + result);
    }

}

